<?php

namespace App\Admin\Controllers;

use App\Admin\Grid\NGrid;
use App\Models\AdminUsersRelatedModel;
use Encore\Admin\Controllers\UserController;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class CompanyController extends UserController
{
    public function title(): string
    {
        return '公司管理';
    }

    public function grid(): NGrid
    {
        $grid = new NGrid(new AdminUsersRelatedModel);
        $grid->model()->leftJoin('admin_users', 'admin_users.id', 'admin_users_related.user_id')
            ->leftJoin('admin_role_users', 'admin_users_related.user_id', 'admin_role_users.user_id')
            ->leftJoin('admin_roles', 'admin_roles.id', 'admin_role_users.role_id')
            ->where('main_id', 0)
            ->select([
                'admin_users.id',
                'admin_users.last_login_at',
                'username', 'admin_users.name as admin_users_name',
                'admin_roles.name as role_name',
                'admin_users_related.created_at',
                'avatar',
            ])->orderByDesc('admin_users_related.id');

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('username', __('stuff.username'))->integer();
                $filter->equal('name', __('stuff.name'))->integer();
            });
        });

        $grid->column('id', 'ID')->sortable();
        $grid->column('username', __('stuff.username'));
        $grid->column('admin_users_name', __('stuff.name'));
        $grid->column('role_name', '角色名称');
        $grid->column('avatar', __('stuff.avatar'))->image('/upload', 100, 100);
        $grid->column('last_login_at', '上一次登录时间');
        $grid->column('created_at', __('l.createdAt'))->display(function ($date) {
            return date('Y-m-d H:i:s', strtotime($date));
        });

        $grid->actions(function (Actions $action) {
            $action->disableEdit(false);
            $action->disableDelete();
            $action->disableView();
        });

        return $grid;
    }

    public function form()
    {
        DB::beginTransaction();
        $form = parent::form();
        $form->saved(function (Form $form) {
            if ($form->isCreating()) {
                AdminUsersRelatedModel::query()->insert([
                    'main_id' => 0,
                    'user_id' => $form->model()->id,
                    'created_at' => Carbon::now(),
                ]);
            }
        });
        DB::commit();
        return $form->confirm('确定提交吗?');
    }
}
